package com.vegetable.modules.controller.stock;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.vegetable.common.utils.R;
import com.vegetable.modules.controller.AbstractController;
import com.vegetable.modules.entity.stock.CostAllocationRecord;
import com.vegetable.modules.entity.stock.Stock;
import com.vegetable.modules.entity.stock.dto.CostAllocationDTO;
import com.vegetable.modules.entity.stock.po.StockQueryPO;
import com.vegetable.modules.service.stock.ICostAllocationService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 库存成本分摊控制器
 * </p>
 *
 * @author Qwen
 * @since 2025-10-17
 */
@Slf4j
@RestController
@RequestMapping("/stock/costAllocation")
@AllArgsConstructor
@Api(value = "库存成本分摊", tags = "库存成本分摊")
public class CostAllocationController extends AbstractController {
    
    private ICostAllocationService costAllocationService;
    
    /**
     * 查询非零库存列表（支持分页）
     */
    @GetMapping("/nonZeroStockList")
    @ApiOperation(value = "查询非零库存列表", notes = "查询数量或重量大于0的库存列表")
    public R<IPage<Stock>> nonZeroStockList(StockQueryPO po) {
        log.info("查询非零库存列表，参数：{}", JSON.toJSONString(po));
        // 使用自定义SQL查询，关联products表获取商品分类信息
        Page<Stock> pageObj = new Page<>(po.getPage() != null ? po.getPage() : 1, po.getLimit() != null ? po.getLimit() : 10);
        
        // 构建查询条件
        Map<String, Object> params = new HashMap<>();
        params.put("commodityName", po.getCommodityName());
        params.put("categoryId", po.getCategoryId());
        params.put("agentName", po.getAgentName());
        params.put("stockBatchNo", po.getStockBatchNo());
        params.put("startTime", po.getStartTime());
        params.put("endTime", po.getEndTime());
        
        // 调用StockService的自定义查询方法
        IPage<Stock> result = costAllocationService.getNonZeroStockWithCategory(pageObj, params);
        return R.data(result);
    }
    
    /**
     * 按重量分摊成本
     */
    @PostMapping("/allocateCostByWeight")
    @ApiOperation(value = "按重量分摊成本", notes = "按重量分摊成本到选中的库存")
    public R<List<String>> allocateCostByWeight(@RequestBody CostAllocationDTO allocationDTO) {
        log.info("按重量分摊成本，参数：{}", JSON.toJSONString(allocationDTO));
        // 设置操作人信息
        allocationDTO.setOperatorId(getUserId());
        allocationDTO.setOperatorName(getUser().getUsername());
        R<List<String>> result = costAllocationService.allocateCostByWeight(allocationDTO);
        return result;
    }
    
    /**
     * 获取库存详情
     */
    @PostMapping("/stockDetails")
    @ApiOperation(value = "获取库存详情", notes = "根据库存ID列表获取库存详情")
    public R<List<Stock>> stockDetails(@RequestBody List<Long> stockIds) {
        log.info("获取库存详情，库存ID列表：{}", JSON.toJSONString(stockIds));
        List<Stock> stocks = costAllocationService.getStockDetails(stockIds);
        return R.data(stocks);
    }
    
    /**
     * 获取库存的分摊记录
     */
    @GetMapping("/allocationRecords/{stockId}")
    @ApiOperation(value = "获取库存的分摊记录", notes = "根据库存ID获取相关的分摊记录")
    public R<List<CostAllocationRecord>> allocationRecords(@PathVariable("stockId") Long stockId) {
        log.info("获取库存的分摊记录，库存ID：{}", stockId);
        List<CostAllocationRecord> records = costAllocationService.getAllocationRecordsByStockId(stockId);
        return R.data(records);
    }
    
    /**
     * 撤销按重量分摊成本
     */
    @PostMapping("/revokeCostAllocationByWeight/{recordId}")
    @ApiOperation(value = "撤销按重量分摊成本", notes = "根据分摊记录ID撤销按重量分摊的成本")
    public R<String> revokeCostAllocationByWeight(@PathVariable("recordId") Long recordId) {
        log.info("撤销按重量分摊成本，分摊记录ID：{}", recordId);
        R<String> result = costAllocationService.revokeCostAllocationByWeight(recordId);
        return result;
    }
}